// blufi.ts
import { ref } from 'vue';
const actualMtu = ref(20);
export const PACKAGE_VALUE = 0x01;
export const PACKAGE_CONTROL_VALUE = 0x00;
export const SUBTYPE_WIFI_MODEl = 0x02;
export const SUBTYPE_SET_SSID = 0x02;
export const SUBTYPE_SET_PWD = 0x03;
export const SUBTYPE_END = 0x03;
export const SUBTYPE_NEG = 0x00;
export const SUBTYPE_SET_SEC_MODE = 0x01;
export const NEG_SET_SEC_TOTAL_LEN = 0x00;
export const NEG_SET_SEC_ALL_DATA = 0x01;
export const DIRECTION_OUTPUT = 0;
export const SUBTYPE_CUSTOM_DATA = 0x13;
export { actualMtu, fetchBLEMTU };


// 过滤设备
export const filterDevice = (devices: any[], name: string) => {
	console.log("发现蓝牙设备")
	console.log(devices)
  return devices.filter(device => /^LanDouBao/.test(device[name]) && device.connectable === true);
};
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// 获取Type
export const getType = (pkgType: number, subType: number) => {
  return (subType << 2) | pkgType;
};

// 获取Frame Control
export const getFrameCTRLValue = (
  encrypted: boolean,
  checksum: boolean,
  direction: number,
  requireAck: boolean,
  frag: boolean
) => {
  let frame = 0;
  if (encrypted) frame |= 1;
  if (checksum) frame |= 1 << 1;
  if (direction === 1) frame |= 1 << 2;
  if (requireAck) frame |= 1 << 3;
  if (frag) frame |= 1 << 4;
  return frame;
};

// 16进制转整形数组
export const hexByInt = (str: string) => {
  const arr: number[] = [];
  if (str.length % 2 !== 0) str = '0' + str;
  for (let i = 0; i < str.length; i += 2) {
    arr.push(parseInt(str.substring(i, i + 2), 16));
  }
  return arr;
};

// 组装数据
export const writeData = (
  type: number,
  subType: number,
  frameCtl: number,
  seq: number,
  len: number,
  data: number[] | null
) => {
  const value: number[] = [];
  const typeVal = getType(type, subType);
  value.push(typeVal);
  value.push(frameCtl);
  value.push(seq);
  value.push(len);
  if (data && data.length > 0) {
    value.push(...data);
  }
  return value;
};

// 分包处理
const fetchBLEMTU = (deviceId: string): Promise<number> => {
  return new Promise(async (resolve) => {
	  
	// 修改蓝牙MTU值
    uni.setBLEMTU({
      deviceId: deviceId,
      mtu: 128,
      success: (res) => {
        console.log(res);
		console.log('设置MTU128成功');
      },
      fail: (res) => {
        console.log(res);
		console.log('设置MTU128失败');
      },
    });

	await delay(500);
    uni.getBLEMTU({
      deviceId,
      success: (res) => {
        const mtu = res.mtu || 23;
        actualMtu.value = mtu;
        console.log(`获取MTU成功: ${mtu} 字节`);
        resolve(mtu);
      },
      fail: (res) => {
        console.warn(`获取MTU失败: ${res.errMsg}, 使用默认值20`);
        actualMtu.value = 23;
        resolve(23);
      }
    });
  });
};

// utils/blufi.ts

// ... (other code remains the same) ...

export const isSubcontractor = (data: number[], checksum: boolean, sequence: number, encrypt: boolean) => {
  // 'data' is expected to be a complete Blufi PDU here.
  // This function's job is to split 'data' if it's too large for a single BLE write.
  let lenData: number[] = [];
  let laveData: number[] = [];
  let flag = false; // True if 'data' (the Blufi PDU) was split for BLE transmission
  const totalLengthOfBlufiPDU = data.length;
  const mtu = actualMtu.value;
  const maxBlePayloadSize = mtu - 3; // 3 bytes for ATT header

  // console.log(`isSubcontractor: PDU total=${totalLengthOfBlufiPDU}, mtu=${mtu}, maxBlePayload=${maxBlePayloadSize}`);

  if (totalLengthOfBlufiPDU > maxBlePayloadSize) {
    flag = true;
    lenData = data.slice(0, maxBlePayloadSize); // First chunk for BLE write
    laveData = data.slice(maxBlePayloadSize);   // Remaining part of the Blufi PDU
  } else {
    flag = false;
    lenData = data; // Send the whole Blufi PDU in one go
    laveData = [];
  }
  return { len: lenData.length, lenData, laveData, flag };
};

// ... (other code remains the same) ...


// 校验和
const assemblyChecksum = (list: number[], len: number, sequence: number) => {
  const checkData: number[] = [sequence, len, ...list];
  const crc = caluCRC(0, checkData);
  const checksumByte1 = crc & 0xff;
  const checksumByte2 = (crc >> 8) & 0xff;
  list.push(checksumByte1, checksumByte2);
  return list;
};

// 计算CRC
const caluCRC = (crc: number, pByte: number[]) => {
  crc = (~crc) & 0xffff;
  const CRC_TB = [
    0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
    // ... 完整CRC表与util.js一致
  ];
  for (const byte of pByte) {
    crc = CRC_TB[((crc & 0xffff) >> 8) ^ (byte & 0xff)] ^ ((crc & 0xffff) << 8);
  }
  return (~crc) & 0xffff;
};